package name.vaccari.matteo.tai.chat.servlet;

import java.sql.Connection;
import java.util.List;

import name.vaccari.matteo.tai.chat.persistence.DatabaseConnector;
import name.vaccari.matteo.tai.chat.persistence.DatabaseExecutor;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.w3c.dom.NodeList;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlUnorderedList;

import static org.junit.Assert.*;


public class IntegrationTest {
	
	@BeforeClass
	public static void setUp() throws Exception {
		Runtime.getRuntime().exec("script/start_in_test_env.sh");
		Thread.sleep(3000);
	}
	
	@AfterClass
	public static void tearDown() throws Exception {
		Runtime.getRuntime().exec("script/stop.sh");
	}
	
	protected void execute(String sql) {
		DatabaseConnector connector = new DatabaseConnector(
				"tai_chat", "tai_chat", "jdbc:mysql://localhost/tai_chat_test", "com.mysql.jdbc.Driver");
		DatabaseExecutor executor = new DatabaseExecutor(connector);
		executor.execute(sql);
	}

	@Test
	public void testPageTitle() throws Exception {
	    final WebClient webClient = new WebClient();
	    final HtmlPage page = webClient.getPage("http://localhost:8080");
	    assertEquals("Ajax Chat!", page.getTitleText());		
	}
	
	@Test
	public void testChatForm() throws Exception {
		setupMessages("primo messaggio", "ultimo messaggio");
		
	    final WebClient webClient = new WebClient();
	    final HtmlPage page = webClient.getPage("http://localhost:8080/messages");
	    String xpath = "//ul";
	    HtmlUnorderedList messages = (HtmlUnorderedList) page.getByXPath(xpath).get(0);
	    NodeList childNodes = messages.getChildNodes();
		assertEquals(2, childNodes.getLength());
	    assertEquals("ultimo messaggio", childNodes.item(0).getTextContent());
	}

	private void setupMessages(String string, String string2) {
		execute("delete from messages");
		insertMessage(string);
		insertMessage(string2);
	}

	private void insertMessage(String text) {
		execute("insert into messages (text, created_at) values ('" + text + "', now())");
	}

}
